using System;
using UnityEngine;


namespace  XYTerrain.Runtime
{
  public class TerrainSoundData : ScriptableObject
  {


    public string  mapId;
    [SerializeField]
    public UInt16[] soundData;
    public Vector3 centerPoint;  //  地形中心点 已经经过 map、size比例缩放 // 暂时规定全部中心点坐标是0，0  
    private float ratio;         // (map/size)
    private Vector2 soundCoord = Vector2.zero;
    public int roundSize;

    public int GetSoundId(Vector2 pos)
    {
      soundCoord.x = pos.x-centerPoint.x;
      soundCoord.y = pos.y-centerPoint.z;


      if (soundCoord.x < 0 || soundCoord.x > roundSize || soundCoord.y < 0 || soundCoord.y > roundSize)
      {
        return 0;
      }
      
      int index = Mathf.RoundToInt(soundCoord.x*ratio ) + Mathf.RoundToInt(soundCoord.y*ratio)*roundSize;
      

      if (index >= soundData.Length||index<0)
      {
         //超出数组边界意味着超出当前地形信息范围 返回 0
         return 0;
      }
      else return (int)soundData[index]; 
    }


    #if UNITY_EDITOR
    public Vector2 GetDebugPos(Vector2 pos)
    {
       return new Vector2(pos.x - centerPoint.x,pos.y-centerPoint.z);
    }
    #endif
    
    public int GetSoundId(Vector3 pos)
    {
      return GetSoundId(new Vector2(pos.x, pos.z));
    }


    //使用位运算进行压缩
    private void BitConver()
    {
      
    }



    public void Init(uint[,] soundData,Terrain  terrain)
    {
      
      Init(soundData);
      var terrainData = terrain.terrainData;
      var t = terrain.transform;
      roundSize = soundData.GetLength(1);
      ratio = (float)terrainData.alphamapWidth / terrainData.size.x;
      // roundSize = terrain.terrainData.size.y  ;
    }

    public void Init(uint[,] soundData,Bounds bound)
    {
      Init(soundData);
      centerPoint = (bound.center - bound.size*0.5f);
      roundSize = Mathf.CeilToInt(bound.size.z);
      ratio = 1;

    }
    
    public void Init(uint[,] soundData)
    {
      CopyArray(soundData);
    }

    public void CopyArray(uint[,] soundData)
    {
      
      int ycount = soundData.GetLength(1);
      int xcount =  soundData.GetLength(0);
      this.soundData = new UInt16[xcount*ycount];

      for (int y = 0; y < ycount; y++)
      {
        for (int x = 0; x < xcount; x++)
        {
          this.soundData[x + y * ycount] = (UInt16)soundData[x, y];
        }
      }
      
    }




  }   
  
}




